package 树;

import 抽象数据类型.TreeNode;

import static 剑指offer.ThreeOrderTraverse.backOrder;
import static 剑指offer.ThreeOrderTraverse.preOrder;


/**
 * @description:
 * @author: ywk
 * @date: 2020-12-17
 */
public class 中序遍历和后序遍历的结果还原一棵二叉树 {
    private static TreeNode buildTree(int[] backOrder, int backStart, int backEnd, int[] midOrder, int midStart, int midEnd) {
        if (backStart < backEnd || midStart > midEnd) return null;
        TreeNode<Integer> root = new TreeNode(backOrder[backStart]);
        int midRoot = findIndex(midOrder, root.val, midStart, midEnd);
        System.out.println(root.val);
        int numsLeft = midRoot - midStart;
        root.left = buildTree(backOrder, midRoot - 1, backEnd, midOrder, midStart, midRoot - 1);
        root.right = buildTree(backOrder, backStart - 1, backEnd + numsLeft, midOrder, midRoot + 1, midEnd);
        return root;
    }

    public static int findIndex(int[] arr, int tar, int start, int end) {
        for (int i = start; i <= end; i++) {
            if (arr[i] == tar) {
                return i;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] houxu = {5, 6, 4, 2, 3, 1};
        int[] zhongxu = {5, 4, 6, 2, 1, 3};
        TreeNode treeNode = buildTree(houxu, zhongxu.length - 1, 0, zhongxu, 0, zhongxu.length - 1);
        System.out.println(preOrder(treeNode));
        System.out.println(backOrder(treeNode));
    }
}
